package com.tangdi.production.mpaychl.service.impl.alipay;

import com.acq.sdk.AlipayConfig;
import com.acq.sdk.Constants;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.tangdi.production.mpaychl.base.service.BaseTranService;
import com.tangdi.production.mpaychl.dao.AlipayConfigMapper;
import com.tangdi.production.mpaychl.dao.AllpayReqContentMapper;
import com.tangdi.production.mpaychl.model.AlipayConfigExample;
import com.tangdi.production.mpaychl.model.AllpayReqContent;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.BusinessException;
import com.tangdi.production.mpbase.exception.TranException;
import com.tangdi.production.mpbase.util.SHAUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <b>Alipay</b>交易[外发]渠道公共处理流程接口实现
 * 
 * @author xiejinzhong 2017/01/13
 *
 */
@SuppressWarnings("unused")
@Service("H5_Alipay")
public class H5AlipayServiceImpl implements BaseTranService {
	private static Logger log = LoggerFactory.getLogger(H5AlipayServiceImpl.class);

	/** 服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 */
	public static String NOTIFY_URL = Constants.REQ_ADDRESS + "/H5-alipay/%s/notify-url.json";
	/** 页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址 */
	public static String RETURN_URL = Constants.REQ_ADDRESS + "/H5-alipay/return-url.json";

	@Autowired
    private AllpayReqContentMapper reqContentMapper;

	@Autowired
	private AlipayConfigMapper alipayConfigMapper;

	@Override
	public Map<String, Object> execute(Map<String, Object> param) throws TranException {
		log.info("进入H5_Alipay处理接口 [{}]", param);

		AlipayConfigExample alipayConfigExample = new AlipayConfigExample();
		alipayConfigExample.or().andStautsEqualTo("1");
		List<com.tangdi.production.mpaychl.model.AlipayConfig> alipayConfigs = alipayConfigMapper.selectByExample(alipayConfigExample);
		com.tangdi.production.mpaychl.model.AlipayConfig alipayConfig = alipayConfigs.get(RandomUtils.nextInt(0, alipayConfigs.size()));

		Map<String,Object> backMap = new HashMap<>();

		String prdordno = "" + param.get("prdordno");
		String ordamt = "" + param.get("ordamt");
		String orderDesc = "" + param.get("orderDesc");
		
		try {
			// 商户订单号，商户网站订单系统中唯一订单号，必填
		    String out_trade_no = prdordno;
			// 订单名称，必填
		    String subject = orderDesc;
		    // 付款金额，必填
		    String total_amount = new BigDecimal(ordamt).movePointLeft(2).toPlainString();
		    // 商品描述，可空
		    String body = orderDesc;
		    // 超时时间 可空
		   String timeout_express="30m";
		    // 销售产品码 必填
		    String product_code="QUICK_WAP_WAY";
		    /**********************/
		    // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签     
		    //调用RSA签名方式
		    AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl()
					, alipayConfig.getAppid()
					, alipayConfig.getRsaPrivateKey()
					, alipayConfig.getFormat()
					, alipayConfig.getCharset()
					, alipayConfig.getAlipayPublicKey()
					, alipayConfig.getSigntype());
		    AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
		    
		    // 封装请求支付信息
		    AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
		    model.setOutTradeNo(out_trade_no);
		    model.setSubject(subject);
		    model.setTotalAmount(total_amount);
		    model.setBody(body);
		    model.setTimeoutExpress(timeout_express);
		    model.setProductCode(product_code);
		    alipay_request.setBizModel(model);
		    // 设置异步通知地址
		    alipay_request.setNotifyUrl(String.format(NOTIFY_URL, alipayConfig.getId()));
		    // 设置同步地址
		    alipay_request.setReturnUrl(RETURN_URL);
		    
		    // form表单生产
		    String form = "";
			try {
				// 调用SDK生成表单
				form = client.pageExecute(alipay_request).getBody();

				if (StringUtils.isNotBlank(form)) {

                    AllpayReqContent record = new AllpayReqContent();
                    record.setHashCode(SHAUtil.SHA(form));
                    record.setOrdNo(prdordno);
                    record.setReqContent(form);
                    record.setCreDttm(new Date());
                    reqContentMapper.insertSelective(record);

                    backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
                    backMap.put("busContent", Constants.REQ_ADDRESS + "/pay/" + SHAUtil.SHA(form) + ".ac");
                    backMap.put("contentType", MsgCT.DATA_TYPE_HTML);
                }
			} catch (AlipayApiException e) {
				log.error(e.getMessage(), e);
			} 
		} catch (Exception e) {
			log.error("渠道调用异常:{}", e.getMessage(), e);
			throw new BusinessException(ExcepCode.EX900001, "执行出错");
		}
		
		return backMap;
	}

	public static void main(String[] args) throws TranException {
		
		Map<String, Object> params = new HashMap<>();
		params.put("ordamt", "100");
		params.put("frontUrl", "http://58.220.30.99:8081/qrcode-starter/returnTest");
		params.put("prdordno", System.currentTimeMillis() + RandomStringUtils.randomAlphabetic(5));
		params.put("orderDesc", "苹果");
		
		Map<String, Object> returnMap = new H5AlipayServiceImpl().execute(params);
		
		System.err.println(returnMap.toString());
		System.out.println(returnMap.get("busContent"));
	}
	
}
